<template>
	<view>
		<view class="page__content">
			<view class="choice-routing__nav">
				<up-navbar :fixed="false" title="选择工艺路线" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
				</up-navbar>
			</view>

			<view class="page__content__main">
				<!-- 非空数据 -->
				<view class="choice-routing__has-data" v-if="PageList.length">
					<m-basic-drag class="choice-routing__list-box" v-model:tableData="PageList" itemKey="index"
						:column="1" itemHeight="100px" height="100%">
						<template #item="{element,index}">
							<view class="choice-routing__item x-f">
								<view class="choice-routing__index x-f">
									<view class="choice-routing__index-badge">
										<text>{{index +1}}</text>
									</view>
								</view>

								<view class="choice-routing__item-content x-f">
									<view class="x-bc"
										style="background-color: #fff;height: 100%;width: 100%;padding: 6px 10px;border-radius: 12px;">
										<view class="choice-routing__left x-f">
											<!-- <up-icon name="minus-circle-fill" color="#f56c6c" size="24"
												@click="deleteListData(element,index)"></up-icon> -->
											<uni-icons type="minus-filled" color="#f56c6c" size="48rpx"
												@click="deleteListData(element,index)"></uni-icons>

											<view v-if="element.Type" class="choice-routing__type-indicator"
												style="height: 100%;background-color: #c6e0fc;padding: 4px 2px;border-radius: 4px;margin-left: 4px;">

												<uni-icons class="choice-routing__icon" color="#209cde"
													fontFamily="CustomFontPlatform"
													size="18">{{uni.$utils.toUniCode('&#xe640;')}}</uni-icons>
											</view>

											<text class="choice-routing__proc-name"
												style="margin-left: 8px;font-size: 28rpx;">{{element.ProcedureName}}</text>

											<!-- 是否外协 -->
											<up-tag v-if="element.Outsource" style="margin-left: 10rpx;" text="外协"
												size="mini" type="warning"></up-tag>

										</view>

										<view class="choice-routing__right x-f" style="height: 100%;">
											<uni-icons type="bars" color="#999" size="40rpx"
												style="margin-right: 6px;"></uni-icons>
											<uni-icons type="compose" color="#999" size="40rpx"
												@click="editCell(element,index)"></uni-icons>
										</view>
									</view>
								</view>
							</view>
						</template>
					</m-basic-drag>

					<!-- 添加工序 -->
					<view class="choice-routing__btn-box x-c" style="margin: 20px 0;">
						<button @click="getProcedure" class="choice-routing__btn choice-routing__btn--outline">
							<uni-icons type="plusempty" color="#51d0d0" size="20"></uni-icons>
							添加工序
						</button>
					</view>

				</view>

				<!-- 空状态 -->
				<view class="choice-routing__empty" v-else>
					<up-empty mode="data" icon="/static/image/Img/DataEmpty.png" text="暂无数据" textColor="#999"
						style="margin: 0 auto;">
						<view class="choice-routing__empty-text-box" style="min-width: 40vw;">
							<button @click="getProcedure"
								class="choice-routing__btn choice-routing__btn--primary btnInitial" type="primary">
								<view class="choice-routing__btn-text">
									<uni-icons type="plusempty" color="#fff" size="20"></uni-icons>
									添加工序
								</view>
							</button>
						</view>
					</up-empty>
				</view>

			</view>

			<view class="page__content__bottom" v-if="PageList.length" :style="uni.$utils.disposeSafeBottomFun()">
				<button class="content_bottom_primary_plainBtn page__content__bottom__btn"
					@click="updataRouting">更新工艺路线</button>
				<button class="content_bottom_primary_Btn page__content__bottom__btn" @click="submitBtn">确定</button>
			</view>
		</view>

		<!-- 更新工艺路线弹层 -->
		<uni-popup class="choice-routing__main-popup" ref="updataPopup" background-color="#fff" :is-mask-click="false">
			<view class="page__content" style="width: 80vw;background-color: #fff;height: auto;">
				<up-navbar :fixed="false" title="更新工艺路线" :autoBack="false" :safeAreaInsetTop="false" leftIcon=" "
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeUpdataRoutingPopup"></uni-icons>
					</view>
				</up-navbar>

				<view class="page__content__main" style="min-height: 200rpx;padding: 0px 20rpx;">

					<up-form labelPosition="left" :model="formData" :rules="rules" ref="updatePopupForm">
						<up-form-item labelWidth="100" label="版本" prop="Versions" leftIcon="order" borderBottom
							:required="uni.$utils.isEmpty(Versions)" :leftIconStyle="{'font-size':'20px'}">
							<up-input v-model="formData.Versions" placeholder="请输入版本号" border="bottom"></up-input>

							<template #right>
								<uni-icons type="help-filled" size="30" @click="openHistoryVersion"
									color="#f8893f"></uni-icons>
							</template>
						</up-form-item>

					</up-form>

				</view>

				<view class="page__content__bottom">
					<view class="x-ec" style="width: 100%;">
						<button class="content_bottom_primary_plainBtn page__content__bottom__btn"
							@click="closeUpdataRoutingPopup">取消</button>
						<button class="content_bottom_primary_Btn page__content__bottom__btn"
							@click="submitUpdataRouting">确定</button>
					</view>
				</view>
			</view>

			<uni-popup class="choice-routing__main-popup" ref="updataPopup_hisVersion" background-color="#fff"
				:is-mask-click="true">
				<view class="choice-routing__popup-container" style="width: 70vw; height: 500rpx;">
					<!-- 顶部导航栏 -->
					<up-navbar :fixed="false" title="历史版本记录" :autoBack="false" :safeAreaInsetTop="false" leftIcon=" "
						leftIconColor="#fff"
						style="width: 100%; background-color: #4ecdc4; color: #fff; border-radius: 8rpx 8rpx 0 0;">
					</up-navbar>
					<!-- 内容区域 -->
					<view class="choice-routing__popup-content" style="flex: 1; overflow: auto; padding: 20rpx;">
						<view class="choice-routing__version-item" v-for="row in hisVersionData" :key="row.Versions">
							<text class="choice-routing__version-label">版本号:</text>
							<text class="choice-routing__version-value">{{row.Versions}}</text>
						</view>
					</view>
				</view>
			</uni-popup>
		</uni-popup>

	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();

	import mBasicDrag from '@/st_ticket/components/m-basic-drag/m-basic-drag';
	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	})

	let formData = reactive<any>({});
	let rules = {
		'Versions': {
			type: 'string',
			required: true,
			message: '工艺路线版本不能为空',
			trigger: ['change']
		},
	}

	const createTicket_routing = ticketStore.createTicket_routing;
	Object.assign(formData, createTicket_routing['formData'])
	let Versions = ref(null)
	let ProcessRouteID = ref(null);

	let PageList = ref<any>([]);
	if (createTicket_routing?.RoutingData.length) {
		PageList.value = createTicket_routing.RoutingData.map((item : any, index : number) => {
			return {
				...item,
				index
			}
		});
		// 记录当前物料版本信息
		formData.Versions = createTicket_routing.RoutingData[0]['Versions']
		Versions.value = createTicket_routing.RoutingData[0]['Versions']

		ProcessRouteID.value = createTicket_routing.RoutingData[0]['ProcessRouteID']
	};
	let FWorkshop = reactive({});
	if (createTicket_routing.FWorkshop) {
		Object.assign(FWorkshop, createTicket_routing.FWorkshop);
	}

	// 主列表 删除按钮
	function deleteListData(data : any, index : number) {
		PageList.value.splice(index, 1)
	}

	// 触发编辑的索引位置
	let editIndex = ref<number | any>(null);
	// 编辑修改工序信息
	function editCell(data : any, index : number) {
		editIndex.value = index;
		mainStore.BaseScreenParm = {
			data: data,
			FWorkshop: FWorkshop
		};
		uni.navigateTo({
			url: './choiceRoutingInfo'
		});
	}

	let routes = getCurrentPages(); //当前页面栈
	const baseScreenListenName = computed(() => {
		return 'choiceRouting_choice_' + routes.length
	})

	// 添加工序
	function getProcedure() {
		mainStore.openBaseScreen({
			allowClear: false, // 清除按钮
			cmd: 'XGD_Procedure', // 接口名
			titleName: "添加工序",
			listeningName: baseScreenListenName.value, // 监听器
			multiple: true,
			serverSearch: { // 查询项
				format: { // 数据映射
					displayValue: "ProcedureName", // 显示值
					hiddenValue: "ProcedureID", // 隐藏值
					pageIndex: "PageIndex", // 分页状态页码字段
					pageSize: "PageSize", // 分页状态每页数量字段
				},
				isPaging: true, //是否分页
				searchKey: 'SearchKey', //搜索关键词，应包含在param中
			},
			param: { // 传递参数
				SearchKey: '',
				PageIndex: 1,
				PageSize: 30
			}
		});
	}

	interface updatePopupInterface {
		open : () => void;
		close : () => void;
	}
	let updataPopup = ref<updatePopupInterface | any>(null)
	interface updatePopupFormInstance {
		validate : (callback ?: (isValid : boolean) => void) => Promise<boolean>
		resetFields : () => void
	}
	let updatePopupForm = ref<updatePopupFormInstance | any>(null)
	// 历史工艺版本数据
	let hisVersionData = ref<any>([]);
	// 更新工艺路线
	function updataRouting() {
		updataPopup.value.open();
	};
	// 关闭工艺路线弹层
	function closeUpdataRoutingPopup() {
		updataPopup.value.close();
		hisVersionData.value = [];
	};
	// 确认工艺版本
	function submitUpdataRouting() {
		updatePopupForm.value.validate().then((res : any) => {
			uni.$utils.showLoading();
			let submitParam = reactive<any>({
				ProcedureID: [],
				WoFWorkshopID: [],
				EquipmentTypeID: [],
				LabourCost: [],
				Outsource: [],
				MoludTypeID: [],
				HourGJ: [],
				ManHour: []
			});
			PageList.value.forEach((item : any) => {
				submitParam.ProcedureID.push(item.ProcedureID || 0)
				submitParam.WoFWorkshopID.push(item.FWorkshopID || 0)
				submitParam.EquipmentTypeID.push(item.EquipmentTypeID || 0)
				submitParam.LabourCost.push(item.LabourCost || 0)
				submitParam.Outsource.push(item.Outsource || 0)
				submitParam.MoludTypeID.push(item.MoludTypeID || 0)
				submitParam.HourGJ.push(item.HourGJ || 0)
				submitParam.ManHour.push(item.ManHour || 0)
			});
			let obj = {
				FType: uni.$utils.isEmpty(Versions.value) ? '新建' : '覆盖',
				IsLinear: formData.IsLinearID,
				ProcessRouteID: ProcessRouteID.value || 0,
				ProductID: formData.ProductID,
				Versions: formData.Versions,
				ProcedureID: submitParam.ProcedureID.join('~'),
				WoFWorkshopID: submitParam.WoFWorkshopID.join('~'),
				EquipmentTypeID: submitParam.EquipmentTypeID.join('~'),
				LabourCost: submitParam.LabourCost.join('~'),
				Outsource: submitParam.Outsource.join('~'),
				MoludTypeID: submitParam.MoludTypeID.join('~'),
				HourGJ: submitParam.HourGJ.join('~'),
				ManHour: submitParam.ManHour.join('~'),
			};

			try {
				request({
					config: {
					},
					url: 'XGD_ProcCreateUpdate',
					method: 'POST',
					data: obj,
					success(ret : any) {
						uni.$utils.hideLoading();
						uni.$utils.msg(ret.data.ds[0]['RMS']);
						closeUpdataRoutingPopup();
					},
					fail(err : any) {
						uni.$utils.hideLoading();
					}
				});
			} catch (error) {
				uni.$utils.hideLoading();
			}


		}).catch((errors : any) => {
			console.log(JSON.stringify(errors))
			if (Array.isArray(errors)) {

				uni.$utils.hideLoading();
				uni.$utils.layer.alert('请填写版本号');
			}
		});
	};
	let updataPopup_hisVersion = ref<updatePopupInterface | any>(null);
	// 显示历史工艺版本信息
	function openHistoryVersion() {
		updataPopup_hisVersion.value.open();

		request({
			config: {
			},
			url: 'XGD_SelectProcedureVerison',
			method: 'POST',
			data: {
				ProductID: formData.ProductID
			},
			success(ret : any) {
				if (ret.status == 200) {
					hisVersionData.value = ret.data.ds;
				}
			}
		});
	};

	// 最终确定按钮
	function submitBtn() {
		let baclData = PageList.value.map((item : any, index : number) => {
			return {
				...item,
				index
			}
		})
		ticketStore.createTicket_routing.RoutingData = baclData;

		uni.$emit(createTicket_routing.listenName, {
			titleName: '工艺路线'
		})
		uni.navigateBack()
	}


	onMounted(() => {
		uni.$on("change_routingEdit", (ret : any) => {
			switch (ret.type) {
				case "工序":
					if (!uni.$utils.isEmpty(editIndex.value)) {
						PageList.value[editIndex.value] = ret.data;

						PageList.value = PageList.value.map((item : any, index : number) => {
							return {
								...item,
								index: index
							}
						});
						editIndex.value = null;
					}
					break;
				default:
					break;
			}
		});

		uni.$on(baseScreenListenName.value, (ret : any) => {
			switch (ret.titleName) {
				case "添加工序":
					let choiceData = ret.data.map((item : any) => {
						return {
							...item,
							Type: 0
						}
					});
					PageList.value.push(...choiceData);

					for (let i = 0; i < PageList.value.length; i++) {
						PageList.value[i]['index'] = i;
					}

					break;
				default:
					break;
			}
		})
	});
	onUnload(() => {
		uni.$off("change_routingEdit");
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;

		/* 全局第三方按钮重置 */
		:deep(uni-button) {
			margin: initial;
		}

		/* filed-like 行样式（保留原语义 FieldBox -> FiledBox） */
		.choice-routing__field {
			position: relative;
			font-size: 16px;
			padding: 10px 15px !important;

			&::after {
				position: absolute;
				box-sizing: border-box;
				content: ' ';
				pointer-events: none;
				right: 16px;
				bottom: 0;
				left: 16px;
				border-bottom: 1px solid #ebedf0;
				-webkit-transform: scaleY(0.5);
				transform: scaleY(0.5);
			}

			&:last-child::after {
				border-bottom: none;
			}
		}

		/* 主容器 */
		&__main {

			/* 兼容 u-cell 内部 body 高度 */
			// :deep(.u-cell__body) {
			// 	height: 100% !important;
			// }

			.choice-routing__item {
				/* #ifdef MP-WEIXIN */
				height: 100px !important;
				/* #endif */

				/* #ifndef MP-WEIXIN */
				height: 100% !important;
				/* #endif */

				.choice-routing__index {
					height: 100%;
					min-width: 60px;
					justify-content: center;

					.choice-routing__index-badge {
						width: 48rpx;
						height: 48rpx;
						background-color: #51d0d0;
						color: #fff;
						border-radius: 48rpx;
						line-height: 48rpx;
						text-align: center;
						font-size: 24rpx;
					}
				}

				.choice-routing__item-content {
					flex: 1;
					height: 100%;
					padding: 10px 16px 10px 6px;
					// background-color: #fff;
				}
			}

			/* 添加按钮容器 */
			.choice-routing__btn-box {
				.choice-routing__btn--outline {
					width: 80%;
					color: #51d0d0;
					background-color: #fff;
					border: 1px solid #51d0d0;
					border-radius: 12px;
				}
			}

			/* 空状态 */
			.choice-routing__main__empty {
				height: 100%;
				padding-top: 10vh;

				.choice-routing__empty-text-box {
					.choice-routing__empty-text {
						text-align: center;
						margin-top: 20px;
						color: #999;
						font-size: 14px;
					}

					.choice-routing__btn--primary {
						width: 100%;
						color: #fff;
						background-color: #51d0d0;
						border-radius: 12px;
						margin-top: 20px;

						.choice-routing__btn-text {
							display: flex;
							align-items: center;
							justify-content: center;
						}
					}
				}
			}
		}

		/* 底部操作 */
		&__bottom {
			border-top: 1px solid #f9f9f9;
		}


		/* 工艺路线详情弹层 */
		&__detail {
			:deep(.u-transition) {
				z-index: 9999 !important;
			}

			.choice-routing__main {
				display: flex;
				flex-direction: column;
				padding-bottom: 20px;

				.choice-routing__list-box {
					/* 保持原样 */
				}
			}
		}

		/* 工序弹层样式 */
		&__gongxu {
			:deep(.u-transition) {
				z-index: 999999 !important;
			}
		}

		/* 复选框样式（保持原样） */
		:deep(.uni-checkbox-input) {
			border: 2px solid #d1d1d1 !important;
		}

		:deep(.uni-checkbox-input-checked) {
			background: #51d0d0;
			color: #fff !important;
			border-color: #51d0d0 !important;
		}


		/* MainPopup 公共样式 */
		.choice-routing__main-popup {
			:deep(.u-transition) {
				z-index: 9999999 !important;
			}

			.choice-routing__main {
				padding: 0px 20rpx;
				flex: 1;
				overflow: auto;
				min-height: 200rpx;
			}

			.choice-routing__popup-bottom {
				justify-content: space-evenly;
				padding: 8rpx 8rpx;
				border-top: 1px solid #ececec;

				:deep(button) {
					width: 44%;

					&:first-child {
						background-color: #fff;
						color: #51d0d0;
						border: 1px solid #51d0d0;
					}

					&:last-child {
						background-color: #51d0d0;
						color: #fff;
					}
				}
			}
		}

		/* 弹层容器样式 */
		.choice-routing__popup-container {
			display: flex;
			flex-direction: column;
			background-color: #fff;
			border-radius: 8rpx;
			box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		}

		/* 内容区域样式 */
		.choice-routing__popup-content {
			background-color: #fff;
		}

		/* 版本项标签样式 */
		.choice-routing__version-label {
			font-size: 28rpx;
			color: #333;
			margin-right: 10rpx;
		}

		/* 版本项值样式 */
		.choice-routing__version-value {
			font-size: 28rpx;
			color: #666;
		}
	}
</style>